home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C17 / Sieve.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  46 lines

  1. //: C17:Sieve.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. #include <string>
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. int main() {
  11.   // Create a 50 char string and set each 
  12.   // element to 'P' for Prime
  13.   string sieveChars(50, 'P');
  14.   // By definition neither 0 nor 1 is prime.
  15.   // Change these elements to "N" for Not Prime
  16.   sieveChars.replace(0, 2, "NN");
  17.   // Walk through the array:
  18.   for(int i = 2;  
  19.     i <= (sieveChars.size() / 2) - 1; i++)
  20.     // Find all the factors:
  21.     for(int factor = 2;
  22.       factor * i < sieveChars.size();factor++)
  23.       sieveChars[factor * i] = 'N';
  24.      
  25.   cout << "Prime:" << endl;
  26.   // Return the index of the first 'P' element:
  27.   int j = sieveChars.find('P');
  28.   // While not at the end of the string:
  29.   while(j != sieveChars.npos) {
  30.     // If the element is P, the index is a prime
  31.     cout << j << " ";
  32.     // Move past the last prime
  33.     j++;
  34.     // Find the next prime
  35.     j = sieveChars.find('P', j);
  36.   }
  37.   cout << "\n Not prime:" << endl;
  38.   // Find the first element value not equal P:
  39.   j = sieveChars.find_first_not_of('P');
  40.   while(j != sieveChars.npos) {
  41.     cout << j << " ";
  42.     j++;
  43.     j = sieveChars.find_first_not_of('P', j);
  44.   }
  45. } ///:~
  46.